package com.business.dashboard.service.impl;

import com.business.dashboard.dao.BusinessPlanDao;
import com.business.dashboard.entity.BusinessPlan;
import com.business.dashboard.service.BusinessPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 商业计划书服务实现类
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@Service
@Transactional
public class BusinessPlanServiceImpl implements BusinessPlanService {

    @Autowired
    private BusinessPlanDao businessPlanDao;

    @Override
    public BusinessPlan createPlan(BusinessPlan plan) {
        // 设置默认值
        if (plan.getUserId() == null) {
            plan.setUserId(0L); // 默认系统用户ID
        }
        if (plan.getStatus() == null) {
            plan.setStatus("draft");
        }
        if (plan.getVersion() == null) {
            plan.setVersion(1);
        }
        if (plan.getViewCount() == null) {
            plan.setViewCount(0);
        }
        if (plan.getDownloadCount() == null) {
            plan.setDownloadCount(0);
        }
        if (plan.getFundingNeeded() == null) {
            plan.setFundingNeeded(BigDecimal.ZERO);
        }
        if (plan.getTeamSize() == null) {
            plan.setTeamSize(1);
        }
        if (plan.getDeleted() == null) {
            plan.setDeleted(0);
        }
        
        plan.setCreatedAt(LocalDateTime.now());
        plan.setUpdatedAt(LocalDateTime.now());
        
        businessPlanDao.insert(plan);
        log.info("商业计划书创建成功，计划书ID: {}, 标题: {}, 用户ID: {}", plan.getId(), plan.getTitle(), plan.getUserId());
        return plan;
    }

    @Override
    public BusinessPlan updatePlan(BusinessPlan plan) {
        if (plan.getId() == null) {
            throw new IllegalArgumentException("计划书ID不能为空");
        }
        
        plan.setUpdatedAt(LocalDateTime.now());
        businessPlanDao.updateById(plan);
        log.info("商业计划书更新成功，计划书ID: {}", plan.getId());
        return plan;
    }

    @Override
    public BusinessPlan getPlanById(Long id) {
        if (id == null) {
            return null;
        }
        return businessPlanDao.selectById(id);
    }

    @Override
    public boolean deletePlan(Long id) {
        if (id == null) {
            return false;
        }
        int result = businessPlanDao.deleteById(id);
        if (result > 0) {
            log.info("商业计划书删除成功，计划书ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public List<BusinessPlan> getPlanList(int page, int size, String keyword, String status, String industry, Long userId) {
        int offset = (page - 1) * size;
        return businessPlanDao.selectPlanList(offset, size, keyword, status, industry, userId);
    }

    @Override
    public long getPlanCount() {
        return businessPlanDao.selectCount(null);
    }

    @Override
    public int getPlanCountByStatus(String status) {
        return businessPlanDao.countByStatus(status);
    }

    @Override
    public int getPlanCountByUserId(Long userId) {
        return businessPlanDao.countByUserId(userId);
    }

    @Override
    public boolean publishPlan(Long id) {
        BusinessPlan plan = getPlanById(id);
        if (plan != null) {
            plan.setStatus("published");
            plan.setUpdatedAt(LocalDateTime.now());
            businessPlanDao.updateById(plan);
            log.info("商业计划书发布成功，计划书ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public boolean completePlan(Long id) {
        BusinessPlan plan = getPlanById(id);
        if (plan != null) {
            plan.setStatus("completed");
            plan.setUpdatedAt(LocalDateTime.now());
            businessPlanDao.updateById(plan);
            log.info("商业计划书完成，计划书ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public boolean archivePlan(Long id) {
        BusinessPlan plan = getPlanById(id);
        if (plan != null) {
            plan.setStatus("archived");
            plan.setUpdatedAt(LocalDateTime.now());
            businessPlanDao.updateById(plan);
            log.info("商业计划书归档成功，计划书ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public String generateShareCode(Long id) {
        BusinessPlan plan = getPlanById(id);
        if (plan != null) {
            String shareCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            plan.setShareCode(shareCode);
            plan.setUpdatedAt(LocalDateTime.now());
            businessPlanDao.updateById(plan);
            log.info("商业计划书分享码生成成功，计划书ID: {}, 分享码: {}", id, shareCode);
            return shareCode;
        }
        return null;
    }

    @Override
    public BusinessPlan getPlanByShareCode(String shareCode) {
        if (shareCode == null || shareCode.trim().isEmpty()) {
            return null;
        }
        return businessPlanDao.selectByShareCode(shareCode);
    }

    @Override
    public boolean updateViewCount(Long id) {
        if (id == null) {
            return false;
        }
        int result = businessPlanDao.updateViewCount(id);
        return result > 0;
    }

    @Override
    public boolean updateDownloadCount(Long id) {
        if (id == null) {
            return false;
        }
        int result = businessPlanDao.updateDownloadCount(id);
        return result > 0;
    }

    @Override
    public List<BusinessPlan> getPopularPlans(int limit) {
        return businessPlanDao.selectPopularPlans(limit);
    }

    @Override
    public String generatePlanFile(Long id, String format) {
        // TODO: 实现文件生成功能（PDF、Word等）
        log.info("生成商业计划书文件，计划书ID: {}, 格式: {}", id, format);
        return "files/business_plan_" + id + "." + format.toLowerCase();
    }

    @Override
    public BusinessPlan duplicatePlan(Long id, Long newUserId) {
        BusinessPlan originalPlan = getPlanById(id);
        if (originalPlan == null) {
            return null;
        }
        
        // 创建副本
        BusinessPlan duplicatedPlan = new BusinessPlan();
        duplicatedPlan.setUserId(newUserId);
        duplicatedPlan.setTitle(originalPlan.getTitle() + " - 副本");
        duplicatedPlan.setCompanyName(originalPlan.getCompanyName());
        duplicatedPlan.setIndustry(originalPlan.getIndustry());
        duplicatedPlan.setBusinessModel(originalPlan.getBusinessModel());
        duplicatedPlan.setTargetMarket(originalPlan.getTargetMarket());
        duplicatedPlan.setProblemStatement(originalPlan.getProblemStatement());
        duplicatedPlan.setSolution(originalPlan.getSolution());
        duplicatedPlan.setUniqueValue(originalPlan.getUniqueValue());
        duplicatedPlan.setMarketSize(originalPlan.getMarketSize());
        duplicatedPlan.setCompetitors(originalPlan.getCompetitors());
        duplicatedPlan.setRevenueModel(originalPlan.getRevenueModel());
        duplicatedPlan.setFundingNeeded(originalPlan.getFundingNeeded());
        duplicatedPlan.setTeamSize(originalPlan.getTeamSize());
        duplicatedPlan.setTimeline(originalPlan.getTimeline());
        duplicatedPlan.setPlanData(originalPlan.getPlanData());
        duplicatedPlan.setTemplateId(originalPlan.getTemplateId());
        
        return createPlan(duplicatedPlan);
    }

    @Override
    public List<BusinessPlan> getAllBusinessPlans() {
        return businessPlanDao.selectList(null);
    }

    @Override
    public BusinessPlan createBusinessPlan(BusinessPlan plan) {
        return createPlan(plan);
    }

    @Override
    public BusinessPlan updateBusinessPlan(BusinessPlan plan) {
        return updatePlan(plan);
    }

    @Override
    public boolean deleteBusinessPlan(Long id) {
        return deletePlan(id);
    }

    @Override
    public BusinessPlan getBusinessPlanById(Long id) {
        return getPlanById(id);
    }

    @Override
    public boolean reviewBusinessPlan(Long id, String status, String comment, Long adminId) {
        BusinessPlan plan = getPlanById(id);
        if (plan != null) {
            plan.setStatus(status);
            plan.setUpdatedAt(LocalDateTime.now());
            businessPlanDao.updateById(plan);
            log.info("商业计划书审核完成，计划书ID: {}, 状态: {}, 审核员: {}", id, status, adminId);
            return true;
        }
        return false;
    }

    @Override
    public boolean batchUpdateStatus(List<Long> ids, String status) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        int updated = 0;
        for (Long id : ids) {
            BusinessPlan plan = getPlanById(id);
            if (plan != null) {
                plan.setStatus(status);
                plan.setUpdatedAt(LocalDateTime.now());
                businessPlanDao.updateById(plan);
                updated++;
            }
        }
        log.info("批量更新商业计划书状态成功，更新数量: {}", updated);
        return updated > 0;
    }

    @Override
    public String exportToPdf(Long id) {
        // TODO: 实现PDF导出功能
        log.info("导出商业计划书PDF，计划书ID: {}", id);
        return "exports/business_plan_" + id + ".pdf";
    }

    @Override
    public Object getBusinessPlanStats() {
        // 简单实现商业计划书统计
        long totalPlans = getPlanCount();
        long draftPlans = getPlanCountByStatus("draft");
        long completedPlans = getPlanCountByStatus("completed");
        long publishedPlans = getPlanCountByStatus("published");

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", totalPlans);
        stats.put("draft", draftPlans);
        stats.put("completed", completedPlans);
        stats.put("published", publishedPlans);
        return stats;
    }

    @Override
    public Object getTrendingIndustries() {
        // TODO: 实现热门行业分析
        List<Map<String, Object>> industries = new ArrayList<>();
        
        Map<String, Object> tech = new HashMap<>();
        tech.put("industry", "科技");
        tech.put("count", 45);
        tech.put("growth", "+12%");
        industries.add(tech);
        
        Map<String, Object> ecommerce = new HashMap<>();
        ecommerce.put("industry", "电商");
        ecommerce.put("count", 38);
        ecommerce.put("growth", "+8%");
        industries.add(ecommerce);
        
        Map<String, Object> education = new HashMap<>();
        education.put("industry", "教育");
        education.put("count", 32);
        education.put("growth", "+15%");
        industries.add(education);
        
        Map<String, Object> medical = new HashMap<>();
        medical.put("industry", "医疗");
        medical.put("count", 28);
        medical.put("growth", "+20%");
        industries.add(medical);
        
        Map<String, Object> finance = new HashMap<>();
        finance.put("industry", "金融");
        finance.put("count", 25);
        finance.put("growth", "+5%");
        industries.add(finance);
        
        return industries;
    }

    @Override
    public long getBusinessPlanCount() {
        return getPlanCount();
    }

    @Override
    public List<BusinessPlan> getUserPlans(Long userId, int page, int size) {
        if (userId == null) {
            return new ArrayList<>();
        }
        int offset = (page - 1) * size;
        return businessPlanDao.selectPlanList(offset, size, null, null, null, userId);
    }
}